import { Component, OnInit, ViewChild, ElementRef, Input, Output, EventEmitter } from '@angular/core';
import { Router } from '@angular/router';
import { CollectionViewer, SelectionChange, DataSource, } from "@angular/cdk/collections";
import { FlatTreeControl } from "@angular/cdk/tree";
import { BehaviorSubject, merge, Observable } from "rxjs";
import { map } from "rxjs/operators";
import { ElectronService } from "../core/services";
import { HttpClient } from "@angular/common/http";
import { BackendService } from "../backend.service";
import { MatSnackBar } from '@angular/material/snack-bar';
import { FileService } from '../file.service';
import * as fileSaver from 'file-saver';
import { ResizedEvent } from 'angular-resize-event';
import { PdfViewerComponent, PDFSource, PDFProgressData, PDFDocumentProxy } from 'ng2-pdf-viewer';
///解决ng2-pdf-viewer在不链接互联网时显示pdf问题
//import * as pdfjs from 'pdfjs-dist';
//pdfjs.GlobalWorkerOptions.workerSrc = 'pdf.worker.min.js';
//经过测试，只在angular.json中加入下面一句，上面的语句不需要，问题也解决
// "scripts": [
//   "node_modules/pdfjs-dist/build/pdf.worker.min.js"
// ],
/** Flat node with expandable and level information */
export class DynamicFlatNode {
  constructor(
    public name: string,
    public fileKey: string,
    public level = 0,
    public expandable = false,
    public isLoading = false,
    public parent: string
  ) { }
}

/**
 * File database, it can build a tree structured Json object from string.
 * Each node in Json object represents a file or a directory. For a file, it has filename and type.
 * For a directory, it has filename and children (a list of files or directories).
 * The input will be a json object string, and the output is a list of `FileNode` with nested
 * structure.
 */
export class DynamicDataSource implements DataSource<DynamicFlatNode> {
  dataChange = new BehaviorSubject<DynamicFlatNode[]>([]);
  get data(): DynamicFlatNode[] {
    return this.dataChange.value;
  }
  set data(value: DynamicFlatNode[]) {
    this._treeControl.dataNodes = value;
    this.dataChange.next(value);
  }

  constructor(
    private _treeControl: FlatTreeControl<DynamicFlatNode>,
    private backend: BackendService
  ) {
    this.initialData();
  }

  connect(collectionViewer: CollectionViewer): Observable<DynamicFlatNode[]> {
    this._treeControl.expansionModel.changed.subscribe((change) => {
      if (
        (change as SelectionChange<DynamicFlatNode>).added ||
        (change as SelectionChange<DynamicFlatNode>).removed
      ) {
        this.handleTreeControl(change as SelectionChange<DynamicFlatNode>);
      }
    });

    return merge(collectionViewer.viewChange, this.dataChange).pipe(
      map(() => this.data)
    );
  }

  disconnect(collectionViewer: CollectionViewer): void { }

  /** Handle expand/collapse behaviors */
  handleTreeControl(change: SelectionChange<DynamicFlatNode>) {
    console.log("handleTreeControl:", change);
    if (change.added) {
      change.added.forEach((node) => this.toggleNode(node, true));
    }
    if (change.removed) {
      change.removed
        .slice()
        .reverse()
        .forEach((node) => this.toggleNode(node, false));
    }
  }

  /**
   * Toggle the node, remove from display list
   */
  toggleNode(node: DynamicFlatNode, expand: boolean) {
    const index = this.data.indexOf(node);
    console.log("toggleNode:", index, expand);
    if (index < 0) {
      // If no children, or cannot find the node, no op
      return;
    }
    node.isLoading = true;
    if (expand) {
      this.backend.getChildren(node).subscribe((result) => {
        if (result.ok) {
          const nodes = result.nodes;
          this.data.splice(index + 1, 0, ...nodes);
          this.dataChange.next(this.data);
          node.isLoading = false;
        }
      });
    } else {
      let count = 0;
      for (
        let i = index + 1;
        i < this.data.length && this.data[i].level > node.level;
        i++, count++
      ) { }
      this.data.splice(index + 1, count);
      // notify the change
      this.dataChange.next(this.data);
      node.isLoading = false;
    }
  }
  findNode(node: DynamicFlatNode): number {
    //自己new出来的node，使用这个方法查找，使用this.data.indexOf(node)不可以
    let index: number = -1;
    let i: number = -1;
    for (let n of this.data) {
      i++;
      if (n.name == node.name && n.parent == node.parent) {
        index = i;
        break;
      }
    }
    return index;
  }
  delNode(node: DynamicFlatNode) {
    console.log("del node begin");
    const index = this.data.indexOf(node);
    let count = 0;
    for (
      let i = index + 1;
      i < this.data.length && this.data[i].level > node.level;
      i++, count++
    ) { }
    this.data.splice(index, count + 1);
    this.dataChange.next(this.data);
  }
  renameNode(curNode: DynamicFlatNode, name: string) {
    curNode.name = name;
    this.dataChange.next(this.data);
  }
  addNode(curNode: DynamicFlatNode, name: string) {
    let newnode: DynamicFlatNode;
    if (curNode) {
      console.log("选中了node，在此node下创建子目录", curNode);
      let index = this.data.indexOf(curNode);
      if (curNode.expandable) {
        //选中的是个目录
        if (this._treeControl.isExpanded(curNode)) {
          newnode = new DynamicFlatNode(name, "", curNode.level + 1, true, false, curNode.parent + "/" + curNode.name)
          if (this.findNode(newnode) == -1) {//如果已经存在了，就不要添加了
            this.data.splice(index + 1, 0, newnode);
          }
        }
        this.expandNode(curNode);
      } else {
        //选中的是个文件
        newnode = new DynamicFlatNode(name, "", curNode.level, true, false, curNode.parent)
        if (this.findNode(newnode) == -1) {//如果已经存在了，就不要添加了
          this.data.splice(index + 1, 0, newnode);
        }
      }
    } else {
      console.log("没有选中node，创建一级目录");
      newnode = new DynamicFlatNode(name, "", 0, true, false, "")
      if (this.findNode(newnode) == -1) {//如果已经存在了，就不要添加了
        this.data.push(newnode);
      }
    }
    this.dataChange.next(this.data);
  }
  nodeIsExpanded(node: DynamicFlatNode): boolean {
    return this._treeControl.isExpanded(node);
  }
  expandNode(node: DynamicFlatNode) {
    if (node && !this.nodeIsExpanded(node)) {
      this._treeControl.expand(node);
    }
  }
  addFile(curNode: DynamicFlatNode, key: string, fileName: string) {
    console.log("datasource addfile", curNode);
    if (curNode) {
      let index = this.data.indexOf(curNode);
      console.log(index);
      if (curNode.expandable) {
        //选中的是个目录
        if (this._treeControl.isExpanded(curNode)) {
          let node = new DynamicFlatNode(fileName, key, curNode.level + 1, false, false, curNode.name);
          if (this.findNode(node) < 0) {
            this.data.splice(index + 1, 0, node);
          }
        }

      } else {
        //选中的是个文件
        let node = new DynamicFlatNode(fileName, key, curNode.level, false, false, curNode.parent);
        if (this.findNode(node) < 0) {
          this.data.splice(index + 1, 0, node);
        }
      }
    } else {
      console.log("没有选中node，不增加文件");
      //this.data.push(new DynamicFlatNode(name, 0, true));
    }
    this.dataChange.next(this.data);
  }
  /** Initial data from database */
  initialData() {
    this.backend.initialData().subscribe((result) => {
      if (result.ok) {
        this.data = result.nodes;
      }
    });
  }
}

@Component({
  selector: "app-home",
  templateUrl: "./home.component.html",
  styleUrls: ["./home.component.scss"]
})
export class HomeComponent implements OnInit {
  constructor(
    public router: Router,
    private fileService: FileService,
    public electron: ElectronService,
    private http: HttpClient,
    public backend: BackendService,
    private _snackBar: MatSnackBar
  ) {
    this.treeControl = new FlatTreeControl<DynamicFlatNode>(
      this.getLevel,
      this.isExpandable
    );
    this.dataSource = new DynamicDataSource(this.treeControl, this.backend);
  }
  ngOnInit(): void {
    //this.backend.username = "admin";//调试程序时打开，刷新页面不会重新登录
    if (!this.backend.username) {
      this.router.navigate(['login']);
    }
  }
  treeControl: FlatTreeControl<DynamicFlatNode>;
  dataSource: DynamicDataSource;
  newnodename: string;
  renamevalue: string;
  getLevel = (node: DynamicFlatNode) => node.level;
  isExpandable = (node: DynamicFlatNode) => node.expandable;
  hasChild = (_: number, _nodeData: DynamicFlatNode) => _nodeData.expandable; //html中用到了
  currFileKey: string;
  activeNode: DynamicFlatNode;
  showpdftools: boolean = false;
  showFindfileCom: boolean = false;
  showExtinfoCom: boolean = false;
  showConfirmDelete: boolean = false;
  showConfirmRename: boolean = false;
  showExport: boolean = false;
  showPdfCom: boolean = false;
  showWaitSpinner: boolean = false;
  searchTxt: string;
  pdfSrc: string | PDFSource | ArrayBuffer;
  navTitle: string;
  delConfirmInfo: string;
  waitinfo: string;

  //////////////////////////////////// pdf 相关begin
  errorPdf: any = true;
  page = 1;
  rotation = 0;
  zoom = 1.0;
  originalSize = false;
  pdf: any;
  renderText = true;
  progressData: PDFProgressData;
  isLoaded = false;
  stickToPage = true;
  showAll = true;
  autoresize = true;
  fitToPage = true;
  outline: any[];
  isOutlineShown = false;
  pdfQuery = '';

  @ViewChild(PdfViewerComponent)
  private pdfComponent: PdfViewerComponent;

  // Load pdf
  loadPdf() {
    const xhr = new XMLHttpRequest();
    xhr.open('GET', '/assets/pdf-test.pdf', true);
    xhr.responseType = 'blob';

    xhr.onload = (e: any) => {
      console.log(xhr);
      if (xhr.status === 200) {
        const blob = new Blob([xhr.response], { type: 'application/pdf' });
        this.pdfSrc = URL.createObjectURL(blob);
      }
    };
    xhr.send();
  }

  incrementPage(amount: number) {
    this.page += amount;
  }

  incrementZoom(amount: number) {
    this.zoom += amount;
  }

  rotate(angle: number) {
    this.rotation += angle;
  }

  /**
   * Render PDF preview on selecting file
   */
  onFileSelected() {
    const $pdf: any = document.querySelector('#file');

    if (typeof FileReader !== 'undefined') {
      const reader = new FileReader();

      reader.onload = (e: any) => {
        this.pdfSrc = e.target.result;
      };

      reader.readAsArrayBuffer($pdf.files[0]);
    }
  }
  //@Output() loadPdfComplete: EventEmitter<boolean> = new EventEmitter<boolean>();
  @Output() pdfSearchComplete: EventEmitter<boolean> = new EventEmitter<boolean>();
  /**
   * Get pdf information after it's loaded
   * @param pdf
   */
  afterLoadComplete(pdf: PDFDocumentProxy) {
    console.log("+++++++++++++++++++++++afterLoadComplete");
    this.loadPdfComplete(true);
    this.showPdfCom = true;
    this.pdf = pdf;
    //this.extinfoPanel.close();
    this.loadOutline();
  }

  /**
   * Get outline
   */
  loadOutline() {
    this.pdf.getOutline().then((outline: any[]) => {
      this.outline = outline;
    });
  }

  /**
   * Handle errorPdf callback
   *
   * @param error
   */
  onErrorPdf(error: any) {
    console.log("+++++++++++++++++++++++onErrorPdf");
    this.loadPdfComplete(false);
    this.showPdfCom = false;
    this.errorPdf = error; // set error
    console.log("onErrorPdf////////////", error);
    if (error.name === 'PasswordException') {
      const password = prompt(
        'This document is password protected. Enter the password:'
      );

      if (password) {
        this.errorPdf = null;
        this.setPassword(password);
      }
    }
  }

  setPassword(password: string) {
    let newSrc;

    if (this.pdfSrc instanceof ArrayBuffer) {
      newSrc = { data: this.pdfSrc };
    } else if (typeof this.pdfSrc === 'string') {
      newSrc = { url: this.pdfSrc };
    } else {
      newSrc = { ...this.pdfSrc };
    }

    newSrc.password = password;

    this.pdfSrc = newSrc;
  }

  /**
   * Pdf loading progress callback
   * @param {PDFProgressData} progressData
   */
  onProgress(progressData: PDFProgressData) {
    //console.log(progressData);
    this.progressData = progressData;

    this.isLoaded = progressData.loaded >= progressData.total;
    this.errorPdf = null; // clear error
  }

  getInt(value: number): number {
    return Math.round(value);
  }

  /**
   * Navigate to destination
   * @param destination
   */
  navigateTo(destination: any) {
    this.pdfComponent.pdfLinkService.navigateTo(destination);
  }

  /**
   * Scroll view
   */
  scrollToPage() {
    this.pdfComponent.pdfViewer.scrollPageIntoView({
      pageNumber: 3
    });
  }

  /**
   * Page rendered callback, which is called when a page is rendered (called multiple times)
   *
   * @param {CustomEvent} e
   */
  pageRendered(e: CustomEvent) {
    //console.log('(page-rendered)', e);
    //this.pdfComponent.pdfViewer.currentScaleValue = 'page-fit';
  }

  searchQueryChanged(newQuery: string) {
    console.log("searchQueryChanged", newQuery);
    if (newQuery == "") {
      this.pdfSearchComplete.emit(true);
      return;
    }

    if (newQuery !== this.pdfQuery) {
      this.pdfQuery = newQuery;
      this.pdfComponent.pdfFindController.executeCommand('find', {
        query: this.pdfQuery,
        highlightAll: true
      });
    } else {
      this.pdfComponent.pdfFindController.executeCommand('findagain', {
        query: this.pdfQuery,
        highlightAll: true
      });
    }
    this.pdfComponent.pdfViewer.eventBus.on('updatefindmatchescount', data => {//文件内容中搜不到时，这个事件不发生
      this.pdfSearchComplete.emit(true);
      //console.log("searchQueryChanged,匹配项目个数：",data.matchesCount.total) ;
    });
  }
  ////////////////pdf 相关 end
  ////////////////////////////////////
  /* Drag and drop */
  dragNode: DynamicFlatNode;
  dragNodeExpandOverWaitTimeMs = 300;
  dragNodeExpandOverNode: any;
  dragNodeExpandOverTime: number;
  dragNodeExpandOverArea: string;
  @ViewChild("emptyItem") emptyItem: ElementRef;

  handleDragStart(event, node) {
    console.log("handleDragStart", node);
    // Required by Firefox (https://stackoverflow.com/questions/19055264/why-doesnt-html5-drag-and-drop-work-in-firefox)
    event.dataTransfer.setData("foo", "bar");
    event.dataTransfer.setDragImage(this.emptyItem.nativeElement, 0, 0);
    this.dragNode = node;
    this.treeControl.collapse(node); //拖动的是文件夹，就先折叠起来，此项目文件夹禁止拖动
  }

  handleDragOver(event, node) {
    console.log("handleDragOver", node);
    event.preventDefault();

    // Handle node expand
    if (node === this.dragNodeExpandOverNode && node.expandable) {
      if (this.dragNode !== node && !this.treeControl.isExpanded(node)) {
        if (
          new Date().getTime() - this.dragNodeExpandOverTime >
          this.dragNodeExpandOverWaitTimeMs
        ) {
          this.treeControl.expand(node);
        }
      }
    } else {
      this.dragNodeExpandOverNode = node;
      this.dragNodeExpandOverTime = new Date().getTime();
    }

    // Handle drag area
    const percentageX = event.offsetX / event.target.clientWidth;
    const percentageY = event.offsetY / event.target.clientHeight;
    if (percentageY < 0.25) {
      this.dragNodeExpandOverArea = "above";
    } else if (percentageY > 0.75) {
      this.dragNodeExpandOverArea = "below";
    } else {
      this.dragNodeExpandOverArea = "center";
    }
  }

  handleDrop(event, node: DynamicFlatNode) {//如果还保留拖放功能，需要修改拖放逻辑
    console.log("handleDrop", node);
    event.preventDefault();
    if (node.parent !== this.dragNode.parent) {
      console.log("从 ", this.dragNode.parent, " 到", node.parent, this.dragNode.name);
      let item = this.dragNode.name;
      let fileName = this.dragNode.name;
      this.backend.copyFile({ sourceNode: this.dragNode, destNode: node }).subscribe(result => {
        console.log(result, item);
        if (result.ok) {
          this.dataSource.addFile(node, item, fileName);
        }
      });
    }
    this.dragNode = null;
    this.dragNodeExpandOverNode = null;
    this.dragNodeExpandOverTime = 0;
  }

  handleDragEnd(event) {
    console.log("handleDragEnd");
    this.dragNode = null;
    this.dragNodeExpandOverNode = null;
    this.dragNodeExpandOverTime = 0;
  }

  //////////////////////////////////////
  clickNode(node: DynamicFlatNode) {
    this.activeNode = node;
    //this.newnodename = node.item;
    //node.item = "click me";
    let path = this.electron.path;
    console.log(node);
    this.showExport = false;
    if (!node.expandable) {
      this.currFileKey = node.fileKey;
      this.showFindfileCom = false;
      this.showExtinfoCom = false;
      this.showPdfCom = true;
      this.navTitle = this.activeNode.parent + ": " + this.activeNode.name;
      this.pdfSrc = "/files/" + this.activeNode.fileKey + ".pdf";
    }
  }
  private highlightWord(searchWord: string, delay: number) {
    this.waitinfo = "正在高亮显示查找的字句，请耐心等待";
    setTimeout(() => {
      this.searchQueryChanged(searchWord);
      this.searchTxt = "";
    }, delay);
    setTimeout(() => {
      this.showWaitSpinner = false;
    }, 6000);//最多找六秒，因为文件内容中找不到searchWord，就不发送pdfSearchComplete事件，无法关闭查找等待提示画面
  }
  clickSearchfile(parm: any) {

    this.showPdfCom = false;
    this.pdfSrc = "";
    this.navTitle = "";

  }
  clickFindedfile(parm: any) {
    this.searchTxt = parm.searchTxt;
    let link: any = parm.link;
    console.log("clickFindfile", parm);
    
    this.showPdfCom = true;
    if (this.currFileKey == link.key) {//已经打开的pdf，不会再次重新加载，没有loadPdfComplete事件
      this.showWaitSpinner = false;
      // this.highlightWord(this.searchTxt, 0);
      // this.searchTxt = "";
    } else {
      this.showWaitSpinner = true;
      if(this.searchTxt==""){//精确查找，不需要高亮显示 查找内容
        this.showWaitSpinner = false;
      }      
      this.currFileKey = link.key;
      this.pdfSrc = "/files/" + this.currFileKey + ".pdf";
      this.navTitle = link.name;
    }
  }
  loadPdfComplete(ok: boolean) {
    console.log("--------------------", ok);
    this.showpdftools = ok;
    if (ok) {
      if (this.showWaitSpinner) {
        this.highlightWord(this.searchTxt, 3000);//loadPdfComplete后立即查找文件，文件内容找不到
      }
    } else {
      this.showWaitSpinner = false;
      console.log("loadPdfComplete出错了")
    }
  }
  refreshNode() {
    console.log("refleshNode", this.activeNode, this.newnodename);
    if (this.activeNode && this.activeNode.expandable) {
      if (this.treeControl.isExpanded(this.activeNode)) {
        this.treeControl.collapse(this.activeNode);
      } else {
        this.treeControl.expand(this.activeNode);
      }
    }
  }
  renameNode(name: string) {
    if (name && name.trim().length > 0) {
      if (name.indexOf("我的文件夹") > -1) {//我的文件夹只能新建，不能重命名为，防止把权限控制保护范围内的文件夹命名成，获得权限
        this._snackBar.open("我的文件夹只能新建，不能重命名其它文件夹成我的文件夹", "知道了", {
          duration: 5 * 1000,
        });
        return;
      }
      if (this.backend.username == "admin" || (this.activeNode && (this.activeNode.name + this.activeNode.parent).indexOf("我的文件夹") > -1)) {
        //this.dataSource.addNode(tempNode, name);
        /////////////////////////////////////////////////
        this.backend.renameNode({ node: this.activeNode, name: name }).subscribe((result) => {
          if (result.ok) {
            this.dataSource.renameNode(this.activeNode, name);
            this.renamevalue = "";
            this.showConfirmRename = false;
          } else {
            this._snackBar.open("修改文件夹名出错了，" + result.message, "知道了", {
              duration: 5 * 1000,
            });
          }
        });

        ///////////////////////////////////////////
      } else {
        this._snackBar.open("不是管理员，不允许新建文件夹", "知道了", {
          duration: 5 * 1000,
        });
      }


    } else {
      this._snackBar.open("输入新建文件夹名称", "知道了", {
        duration: 5 * 1000,
      });
    }
  }
  addNode(name: string) {
    if (name && name.trim().length > 0) {
      let tempCurNodeNode: DynamicFlatNode = this.activeNode;
      if (this.backend.username == "admin"||name.indexOf("我的文件夹") > -1 || (this.activeNode && (this.activeNode.name + this.activeNode.parent).indexOf("我的文件夹") > -1)) {
        //this.dataSource.addNode(tempNode, name);
        /////////////////////////////////////////////////
        this.backend.addNode({ node: tempCurNodeNode, name: name }).subscribe((result) => {
          if (result.ok) {
            this.dataSource.addNode(tempCurNodeNode, name);
            this.newnodename = "";
          } else {
            this._snackBar.open("新建文件夹出错了，" + result.message, "知道了", {
              duration: 5 * 1000,
            });
          }
        });

        ///////////////////////////////////////////
      } else {
        this._snackBar.open("不是管理员，不允许新建文件夹", "知道了", {
          duration: 5 * 1000,
        });
      }


    } else {
      this._snackBar.open("输入新建文件夹名称", "知道了", {
        duration: 5 * 1000,
      });
    }

  }
  showRenameNode() {
    if (this.activeNode && this.activeNode.expandable) {
      this.showConfirmRename = true;
    } else {
      this.showConfirmRename = false;
    }
  }
  showConfirmDelNode() {
    if (this.activeNode) {
      this.showConfirmDelete = true;
      this.delConfirmInfo = "确认删除 " + this.activeNode.name + " 吗？";
    } else {
      console.log("选中要删除的node");
      this._snackBar.open("选中要删除的文件夾", "知道了", {
        duration: 5 * 1000,
      });
    }
  }
  delNode() {
    if (this.activeNode) {
      console.log("删除节点：", this.activeNode);

      //this.dataSource.delNode(this.activeNode);
      this.backend.delNode(this.activeNode).subscribe((result) => {
        if (result.ok) {
          this.showConfirmDelete = false;
          this.dataSource.delNode(this.activeNode);
          this.activeNode = null;
          this.currFileKey = "";
          this.showPdfCom = false;
        } else {
          this._snackBar.open("删除的文件夾出错了，" + result.message, "知道了", {
            duration: 5 * 1000,
          });
        }
      });

    } else {
      console.log("选中要删除的node");
      this._snackBar.open("选中要删除的文件夾", "知道了", {
        duration: 5 * 1000,
      });
    }
  }
  addFile(event: Event) {
    if (event) {
      event.stopPropagation();
    }
    //console.log(this.electron.remote);
    let dialog = this.electron.remote.dialog;

    //let dialog = this.electron.remote.require("dialog");
    if (!this.activeNode) {
      console.log("选择一个目标文件夹，再添加文件");
      this._snackBar.open("选择一个目标文件夹，再添加文件", "知道了", {
        duration: 5 * 1000,
      });
      return;
    }

    dialog.showOpenDialog({ properties: ["openFile", "multiSelections"], filters: [{ name: 'PDF', extensions: ['pdf'] }] })
      .then((sourceFiles) => {
        if (sourceFiles === undefined) {
          console.log("You didn't select the file");
          return;
        }
        console.log(sourceFiles);
        this.waitinfo = "正在解析新增加的文件内容，请耐心等待"
        this.showWaitSpinner = true;
        this.backend.addFile({ node: this.activeNode, files: sourceFiles.filePaths })
          .subscribe((result) => {
            this.showWaitSpinner = false;
            console.log("backend addfile", result);
            if (result.ok) {
              for (let file of result.okfiles) {
                console.log(file);
                this.dataSource.addFile(this.activeNode, file.fileKey, file.fileName);
              }
              this.dataSource.expandNode(this.activeNode);
              if (result.errfiles.length > 0) {
                this._snackBar.open("文件格式错误，添加被拒绝：" + result.errfiles.join("，"), "知道了", {
                  duration: 10 * 1000,
                });
              }

            } else {
              console.log("backend addfile result.ok", result.ok);
            }
          });
      });
  }
  importData() {
    if (this.activeNode && !this.activeNode.expandable) {
      console.log("选择一个目标文件夹,再进行导入");
      this._snackBar.open("选择一个目标文件夹,再进行导入", "知道了", {
        duration: 5 * 1000,
      });
      return;
    }
    let dialog = this.electron.remote.dialog;
    dialog.showOpenDialog({ properties: ["openFile"], filters: [{ name: 'ZID', extensions: ['zid'] }] })
      .then((sourceFiles) => {
        if (sourceFiles === undefined) {
          console.log("You didn't select the file");
          return;
        }
        console.log(sourceFiles);
        this.backend.importData({ node: this.activeNode, files: sourceFiles.filePaths })
          .subscribe((result) => {
            console.log("backend importData", result);
            if (result.ok) {
              console.log("导入数据成功", result);
              this.dataSource.addNode(this.activeNode, result.nodename);
              // for (let file of result.okfiles) {
              //   console.log(file);
              //   this.dataSource.addFile(this.activeNode, file.fileKey, file.fileName);
              // }

            } else {
              console.log("backend importData result.ok", result.ok);
            }
          });
      });
  }
  exportButtonClick() {
    if (this.activeNode.expandable) {
      this.showExport = true;
    } else {
      this.downloadFile(this.activeNode.fileKey, this.activeNode.name);
    }
  }
  exportFiles() {//断言选中的是文件夹
    let dialog = this.electron.remote.dialog;
    dialog.showOpenDialog({ properties: ["openDirectory"] })
      .then((sourceFiles) => {
        if (sourceFiles === undefined) {
          console.log("You didn't select the file");
          return;
        }
        let destPath = sourceFiles.filePaths[0];
        console.log("select directory", sourceFiles.filePaths[0]);
        this.backend.exportFiles({ node: this.activeNode, toDestPath: destPath }).subscribe(result => {
          console.log(result);
          let retstr: string;
          if (result.ok) {
            retstr = "文件数据导出完成，请到选择的文件夹中查看！";
          } else {
            retstr = "文件数据导出失败！";
          }
          this._snackBar.open(retstr, "知道了", {
            duration: 5 * 1000,
          });
        });
      });

  }
  exportData() {//断言选中的是文件夹
    console.log("导出文件夹：", this.activeNode.name);
    this.backend.exportData(this.activeNode).subscribe(result => {
      if (result.ok) {
        console.log("导出的文件夹压缩文件：", result.zipfileName);
        let fileurl: string = "files/download/" + result.zipfileName;
        console.log(fileurl);
        this.fileService.downloadFile(fileurl).subscribe(response => {
          let blob: any = new Blob([response.blob()], { type: 'application/zip' });

          fileSaver.saveAs(blob, result.zipfileName);
        }), error => console.log('Error downloading the file'),
          () => console.info('File downloaded successfully');
      } else {
        console.log("导出文件夹错误，", result.message);
      }
    })

  }
  private downloadFile(fileKey: string, fileName: string) {
    let fileurl: string = "files/" + fileKey + ".pdf";
    console.log(fileurl);
    this.fileService.downloadFile(fileurl).subscribe(response => {
      let blob: any = new Blob([response.blob()], { type: 'application/pdf' });
      //const url= window.URL.createObjectURL(blob);
      //window.open(url);
      //window.location.href = response.url;     
      fileName += ".pdf";
      fileSaver.saveAs(blob, fileName);
    }), error => console.log('Error downloading the file'),
      () => console.info('File downloaded successfully');
  }

  onResized(event: ResizedEvent) {
    //console.log("onResized:0",event);
    // this.width = event.newWidth;
    // this.height = event.newHeight;
  }
  searchButtonClick() {
    this.showExtinfoCom = false;
    this.showFindfileCom = !this.showFindfileCom;
    if (this.showFindfileCom) {
      this.showPdfCom = false;
    }
  }
}
